#!/usr/bin/python3
# coding=utf-8

import os
import yaml
import warnings


class YamlUtil:

    def __init__(self, yaml_file="./configs/setting.yml"):
        self._data = None
        self._yml_file = None
        if os.path.exists(yaml_file):
            self._yml_file = yaml_file
        else:
            raise FileNotFoundError("文件: {} 不存在.".format(yaml_file))

    def data_load(self):
        """读取YAML文件内容
        Returns: 返回一个dict, 适用于yaml文件中只有一个文档。
        """
        with open(self._yml_file, "r", encoding="utf-8") as f:
            self._data = yaml.safe_load(f)

        return self._data

    def data_all_load(self):
        """读取YAML文件内容
        Returns: 返回一个list，适用于yaml文件中含多个文档。
        """
        with open(self._yml_file, "r", encoding="utf-8") as f:
            self._data = list(yaml.safe_load_all(f))

        return self._data

    def data_append(self, exp_data):
        """写入内容到YAML文件中

        Args:
            exp_data (_type_): dict or list

        Raises:
            TypeError: 不推荐的格式
        """
        if isinstance(exp_data, list) or isinstance(exp_data, dict):
            with open(self._yml_file, "a", encoding="utf-8") as f:
                yaml.safe_dump(exp_data, f)
        elif isinstance(exp_data, str):
            warnings.warn(
                "不推荐将Str直接写入YAML文件。因为再次读取的时候, 存在读取异常的风险",
                UserWarning,
            )
            with open(self._yml_file, "a", encoding="utf-8") as f:
                yaml.safe_dump(exp_data, f)

        else:
            raise TypeError("不推荐的格式")

    def data_truncate(self):
        """清空指定YAML文件的内容"""
        with open(self._yml_file, "w") as f:
            f.truncate()


if __name__ == "__main__":
    yml_file = "./configs/setting.yml"
    yml_tmp_file = "./configs/runtime_setting.yml"
    ymlObj = YamlUtil(yml_tmp_file)
    data_dict_demo = {"env": "SIT", "header": {"Content-Type": "application/json"}}
    data_list_demo = [
        {"user_name": "a1"},
        {"user_info": {"name": "a1", "age": 12, "birthday": "2000-01-01"}},
    ]
    data_str_demo = "account: 123"
    ymlObj.data_truncate()
    ymlObj.data_append(data_list_demo)
    print(ymlObj.data_all_load())
    # ----
    ymlObj.data_truncate()
    ymlObj.data_append(data_dict_demo)
    print(ymlObj.data_all_load())
    # ----
    ymlObj.data_truncate()
    ymlObj.data_append(data_str_demo)
    print(ymlObj.data_load())
    # ---
    ymlObj.data_truncate()
